package com.heima.miniofile.service.Impl;

import com.heima.miniofile.constants.MinioConstants;
import com.heima.miniofile.properties.MinIoConfigProperties;
import com.heima.miniofile.service.MinIoFileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author lin
 * @since 2025/6/11
 */
@Service
public class MinIoFileStorageServiceImpl implements MinIoFileStorageService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinIoConfigProperties minIOConfigProperties;
    private final static String separator = "/";
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MinIoFileStorageServiceImpl.class);


    /**
     * @param dirPath 文件路径
     * @param filename yyyy/mm/dd/file.jpg
     * @return 文件全路径
     */
    public String builderFilePath(String dirPath, String filename) {
        StringBuilder stringBuilder = new StringBuilder(50);
        if (!StringUtils.isEmpty(dirPath)) {
            stringBuilder.append(dirPath).append(separator);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String todayStr = sdf.format(new Date());
        stringBuilder.append(todayStr).append(separator);
        stringBuilder.append(filename);
        return stringBuilder.toString();
    }

    /**
     * 上传图片文件
     *
     * @param prefix      文件前缀
     * @param filename    文件名
     * @param inputStream 文件流
     * @return 文件全路径
     */
    @Override
    public String uploadImgFile(String prefix, String filename, InputStream inputStream) {
        String filePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType(MinioConstants.CONTENT_TYPE_PNG)
                    .bucket(minIOConfigProperties.getBucket()).stream(inputStream, inputStream.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            return minIOConfigProperties.getReadPath() + separator +
                    minIOConfigProperties.getBucket() + separator + filePath;
        } catch (Exception ex) {
            log.error("minio put file error.", ex);
            throw new RuntimeException("上传文件失败" + ex.getMessage());
        }
    }

    /**
     * 上传html文件
     *
     * @param prefix      文件前缀
     * @param filename    文件名
     * @param inputStream 文件流
     * @return 文件全路径
     */
    @Override
    public String uploadHtmlFile(String prefix, String filename, InputStream inputStream) {
        String filePath = builderFilePath(prefix, filename);
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .object(filePath)
                    .contentType(MinioConstants.CONTENT_TYPE_HTML)
                    .bucket(minIOConfigProperties.getBucket()).stream(inputStream, inputStream.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            return minIOConfigProperties.getReadPath() + separator +
                    minIOConfigProperties.getBucket() + separator + filePath;
        } catch (Exception ex) {
            log.error("minio put file error.", ex);
            throw new RuntimeException("上传文件失败");
        }
    }

    /**
     * 删除文件
     *
     * @param pathUrl 文件全路径
     */
    @Override
    public void delete(String pathUrl) {
        if (pathUrl == null || pathUrl.trim().isEmpty() || !pathUrl.startsWith("http")) {
            log.warn("无效的文件路径: {}", pathUrl);
            return;
        }
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");
        int separatorIndex  = key.indexOf(separator);

        if (separatorIndex == -1) {
            log.error("无效的MinIO路径格式，缺少分隔符: {}", pathUrl);
            return;
        }
        String bucket = key.substring(0, separatorIndex );
        String filePath = key.substring(separatorIndex  + 1);

        // 删除Objects
        RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder()
                .bucket(bucket)
                .object(filePath)
                .build();

        try {
            minioClient.removeObject(removeObjectArgs);
            log.info("成功删除文件: {}", pathUrl);
        } catch (Exception e) {
            log.error("minio remove file error.  pathUrl:{}", pathUrl);
        }
    }


    /**
     * 下载文件
     *
     * @param pathUrl 文件全路径
     * @return 文件流
     */
    @Override
    public byte[] downLoadFile(String pathUrl) {
        String key = pathUrl.replace(minIOConfigProperties.getEndpoint() + "/", "");
        int index = key.indexOf(separator);
        String filePath = key.substring(index + 1);
        InputStream inputStream = null;
        try {
            inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());
        } catch (Exception e) {
            log.error("minio down file error.  pathUrl:{}", pathUrl);
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while (true) {
            if (inputStream == null) {
                log.warn("InputStream is null during read for file: {}", filePath);
                break;
            }
            try {
                if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
            } catch (IOException e) {
                log.error("Error reading from InputStream for file: {}, error: {}", filePath, e.getMessage(), e);
            }
            byteArrayOutputStream.write(buff, 0, rc);
        }
        return byteArrayOutputStream.toByteArray();
    }
}
